package com.huosu.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.huosu.commons.response.ApiResult;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * @program: miner-shield-web-v2
 * @description:
 * @author: changlin
 * @create: 2019-12-13 11:08
 **/
@Slf4j
public class HttpUtil {

    //超时时间
    public static int timeout = 20000;

//    public static ApiResult post(String url, Map map,int timeout) {
//        String result = "";
//        try {
//            result = HttpRequest.post(url)
//                    .timeout(timeout)
//                    .body(JSONUtil.parse(map))
//                    .execute().body();
//        } catch (Exception e) {
//            return ApiResult.fail(-200, "http请求异常" + e.getMessage());
//        }
//        return ApiResult.ok(result);
//    }
//
//    public static ApiResult post(String url, Map map) {
//        String result = "";
//        try {
//            result = HttpRequest.post(url)
//                    .timeout(timeout)
//                    .body(JSONUtil.parse(map))
//                    .execute().body();
//        } catch (Exception e) {
//            return ApiResult.fail(-200, "http请求异常" + e.getMessage());
//        }
//        return ApiResult.ok(result);
//    }

    public static ApiResult post(String url, List<Map<String, Object>> list) {
        String result = "";
        try {
            result = HttpRequest.post(url)
                    .timeout(timeout)
                    .body(JSONObject.toJSONString(list))
                    .execute().body();
        } catch (Exception e) {
            return ApiResult.fail(-200, "http post请求异常" + e.getMessage());
        }
        return ApiResult.ok(result);
    }

    public static ApiResult get(String url) {
        String result = "";
        try {
            result = HttpRequest.get(url)
                    .timeout(timeout)
                    .execute().body();
        } catch (Exception e) {
            return ApiResult.fail(-200, "http get请求异常" + e.getMessage());
        }
        return ApiResult.ok(result);
    }

    /**
     * 获取网络情况
     *
     * @return
     */
    public static String getNetworkState() {
        String result = "0";
//        try {
//            URL url = new URL("http://www.baidu.com");
//            InputStream in = url.openStream();
//            in.close();
//            result = "1";
//        } catch (Exception e) {
//            log.error("####网络情况 err：{}", e.getMessage());
//        }
        try {
            HttpRequest.get("https://www.baidu.com")
                    .timeout(5000)
                    .execute();
            result = "1";
        } catch (Exception e) {
            log.error("#### 网络情况异常：{}", e.getMessage());
        }
        return result;
    }

}
